import threading
import time
from threading import Timer

import matplotlib.pyplot as plt
import pandas as pd
from DirMonitor import DirMonitor
from TopFrameParser import TopFrameParser
import matplotlib.dates as mdates

is_quit: bool = False


def handle_close(event):
    global is_quit
    print('handle_close')
    is_quit = True


def th_task():
    global is_quit
    while not is_quit:
        print(is_quit)
        update()
        time.sleep(1)


def update():
    global df
    added_files = dm.watch_changes()
    if len(added_files) == 0:
        return
    frames = TopFrameParser.parse_files(added_files)
    df = df.append(frames)
    df = df.sort_index()
    print(df)
    # ax.plot(df.index, df['dashcam'], lw=1, linestyle='--')
    df.plot(ax=ax, grid=True, style=['--', '-.'], subplots=True, layout=(2, 1))
    plt.pause(0.5)


if __name__ == '__main__':
    plt.ion()
    fig = plt.figure()
    fig.canvas.mpl_connect('close_event', handle_close)
    ax = fig.add_subplot(111)  # Create an axes.
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
    plt.gcf().autofmt_xdate()

    df = pd.DataFrame()
    dm = DirMonitor('/home/ole/workspace/1_project/9010/JIRA/fps/top')
    update()
    update_task = threading.Thread(target=th_task, daemon=True)
    update_task.start()
    plt.show()
    update_task.join()
